import i18n from '@/lang';
import store from '@/store';
import Vue from 'vue'

// let dialogInstance = null

// TOTEST 需测试是否兼容移动端浏览器
export const clipboard = {
	async copy(text) {
		// 新浏览器使用API
		if (navigator.clipboard) {
			try {
				return await navigator.clipboard.writeText(text);
			} catch (err) {
				console.error('Async clipboard copy failed:', err);
				return await this.legacyCopy(text);
			}
		}
		return this.legacyCopy(text);
	},

	legacyCopy(text) {
		return new Promise((resolve, reject) => {
			// 创建临时textarea
			const textarea = document.createElement('textarea');
			textarea.value = text;
			textarea.style.position = 'fixed';
			textarea.style.left = '-9999px';

			document.body.appendChild(textarea);
			textarea.select();

			try {
				// 兼容老版本iOS
				const success = document.execCommand('copy');
				document.body.removeChild(textarea);
				success ? resolve() : reject(new Error('Copy failed'));
			} catch (err) {
				document.body.removeChild(textarea);
				reject(err);
			}
		});
	},
	async paste() {
		// 新浏览器使用API
		if (navigator.clipboard) {
			try {
				return await navigator.clipboard.readText();
			} catch (err) {
				console.error('Async clipboard read failed:', err);
				return this.legacyPaste();
			}
		}
		return this.legacyPaste();
	},

	legacyPaste() {
		return new Promise((resolve) => {
			console.log('开始传统粘贴方法');
			const input = document.createElement('input');
			input.style.cssText = `
			position: fixed;
			top: 10%;
			left: 50%;
			transform: translateX(-50%);
			width: 200px;
			height: 20px;
			opacity: 0.01;
			z-index: 9999;
		  `;

			input.addEventListener('paste', (e) => {
				console.log('捕获到粘贴事件', e.clipboardData.types);
				const content = e.clipboardData.getData('text/plain');
				console.log('获取到的文本内容:', content);
				resolve(content);
				document.body.removeChild(input);
			}, { once: true });

			document.body.appendChild(input);
			input.focus();
			console.log('输入框已聚焦');

			setTimeout(() => {
				if (document.body.contains(input)) {
					console.warn('粘贴超时');
					resolve(null);
					document.body.removeChild(input);
				}
			}, 1000);
		});
	}
};

export const langList = [
	{ title: 'English', label: '英语', value: 'en' },
	{ title: '日本語', label: '日语', value: 'ja' },
	{ title: '한국인', label: '韩语', value: 'ko' },
	{ title: 'แบบไทย', label: '泰语', value: 'th' },
	{ title: 'Tiếng Việt ', label: '越南语', value: 'vi' },
	{ title: 'українська', label: '乌克兰语', value: 'uk' },
	{ title: 'Bahasa Indonesia', label: '印度尼西亚语', value: 'ids' },
	{ title: 'Français', label: '法语', value: 'fr' },
	{ title: 'русский', label: '俄语', value: 'ru' },
	{ title: 'Svenska', label: '瑞典语', value: 'sv' },
	{ title: 'Norsk', label: '挪威语', value: 'no' },
	{ title: 'Suomi', label: '芬兰语', value: 'fi' },
	{ title: 'Dansk', label: '丹麦语', value: 'da' },
	{ title: 'Español', label: '西班牙语', value: 'es' },
	{ title: 'Deutsch', label: '德语', value: 'de' },
	{ title: 'العربية', label: '阿拉伯语', value: 'ar' },
	{ title: 'Polski', label: '波兰语', value: 'pl' },
	{ title: 'Hrvatski', label: '克罗地亚语', value: 'hr' },
	{ title: 'Magyar', label: '匈牙利语', value: 'hu' },
	{ title: 'فارسی', label: '波斯语', value: 'fa' },
	{ title: 'Türkçe', label: '土耳其语', value: 'tr' },
	{ title: 'Nederlands', label: '荷兰语', value: 'nl' },
	{ title: 'Português', label: '葡萄牙语', value: 'pt' },
	{ title: 'Italiano', label: '意大利语', value: 'it' },
	{ title: 'Čeština', label: '捷克语', value: 'cs' },
	{ title: 'Български', label: '保加利亚语', value: 'bg' },
	{ title: 'Slovenščina', label: '斯洛伐克语', value: 'sk' },
	{ title: '简体中文', label: '简体中文', value: 'zh_CN' },
	{ title: '繁體中文', label: '繁体中文', value: 'zh_TW' }
];

export const drawingType = [
	{ id: 0, name: '古风' },
	{ id: 1, name: '二次元' },
	{ id: 2, name: '卡通画' },
	{ id: 3, name: '写实风格' },
	{ id: 4, name: '水彩画' },
	{ id: 5, name: '油画' },
	{ id: 6, name: '探索无限' },
	{ id: 7, name: '未来主义' },
	{ id: 8, name: '像素风格' },
	{ id: 9, name: '赛博朋克' },
	{ id: 10, name: '洛丽塔风格' },
	{ id: 11, name: '巴洛克风格' },
	{ id: 12, name: '超现实主义' },
	{ id: 13, name: '蒸汽波艺术' },
	{ id: 14, name: '浮世绘' },
	{ id: 15, name: 'low poly' },
	{ id: 16, name: '概念艺术' },
]

// 处理后端返回i18n数据
export function processI18nKeys(obj, i18nMessage) {
	// 处理数组情况
	if (Array.isArray(obj)) {
		return obj.map(item => processI18nKeys(item, i18nMessage));
	}

	// 处理对象情况
	if (typeof obj === 'object' && obj !== null) {
		const result = {};
		const langPrefix = i18nMessage ? `${i18nMessage.toLowerCase()}_` : '';

		for (const key in obj) {
			if (key.startsWith(langPrefix)) {
				const newKey = key.replace(langPrefix, '');
				result[newKey] = processI18nKeys(obj[key], i18nMessage);
			} else if (key === i18nMessage) {
				result['data'] = processI18nKeys(obj[key], i18nMessage);
			} else {
				result[key] = processI18nKeys(obj[key], i18nMessage);
			}
		}

		return result;
	}

	// 基本类型直接返回
	return obj;
}

// 处理数字为美式格式
export function formatNumberWithCommas(num) {
	// 转换为字符串并移除可能存在的逗号
	const numStr = String(num).replace(/,/g, '');

	// 检查是否为有效数字
	if (isNaN(numStr)) return num;

	// 分割整数和小数部分
	const parts = numStr.split('.');
	let integerPart = parts[0];
	const decimalPart = parts.length > 1 ? `.${parts[1]}` : '';

	// 添加千分位逗号
	integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');

	return integerPart + decimalPart;
}

// 弹窗初始化
// export function initDialog() {
// 	const DialogComponent = Vue.extend(require('@/components/comConfirmDialog').default)
// 	dialogInstance = new DialogComponent().$mount()
// 	document.body.appendChild(dialogInstance.$el)
// }
// 弹窗调用
export function confirmDialog(options) {
	// if (!dialogInstance) {
	// 	initDialog()
	// }
	const DialogComponent = Vue.extend(require('@/components/comConfirmDialog').default)
	let dialogInstance = new DialogComponent({
		store: store, // 确保store传递给组件
		i18n: i18n
	}).$mount()
	document.body.appendChild(dialogInstance.$el)
	options.hasGoogleAuthenticator = store.state.userStore.hasGoogleAuthenticator
	return dialogInstance.open(options)
}

export const scrollListener = {
	handlers: [],
	
	// 添加滚动监听
	addListener(handler) {
		this.handlers.push(handler)
		if (this.handlers.length === 1) {
			window.addEventListener('scroll', this.handleScroll)
		}
	},
	
	// 移除滚动监听
	removeListener(handler) {
		this.handlers = this.handlers.filter(h => h !== handler)
		if (this.handlers.length === 0) {
			window.removeEventListener('scroll', this.handleScroll)
		}
	},
	
	// 处理滚动事件
	handleScroll() {
		const scrollY = window.scrollY
		const scrollX = window.scrollX
		this.handlers.forEach(handler => {
			handler({ scrollY, scrollX })
		})
	}
}

// 确保handleScroll的this指向正确
scrollListener.handleScroll = scrollListener.handleScroll.bind(scrollListener)